<?php

// SimpleComet v1.0 by Mandor <mandor@mandor.net>
// For more info, see http://www.mandor.net/2008/12/23/12

class SimpleComet {

	// Constructor, does the necessary preparations.
	function SimpleComet() {

		// Sets some cache busting headers.
		header('Cache-Control: no-cache, must-revalidate');
		header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');

		// Attempts to disable every possible output buffer and turn on implicit flush.
		@apache_setenv('no-gzip', 1);
		@ini_set('zlib.output_compression', 0);
		@ini_set('implicit_flush', 1);
		for ($i = 0; $i < ob_get_level(); $i++) { ob_end_flush(); }
		ob_implicit_flush(1);

		// Determines the proper technique based on browser type.
		$this->cometTechnique = preg_match('/(Firefox|Safari)/', $_SERVER['HTTP_USER_AGENT']) ? 1 : 2;

		// Some browsers have a buffer we need to fill before incremental rendering kicks in.
		echo '<pre>'.file_get_contents(dirname(__FILE__).'/simplecomet.logo.txt').'</pre>'."\n\n";
		if (strpos($_SERVER['HTTP_USER_AGENT'], 'Chrome') !== false) {
			// Google Chrome has an even bigger buffer so we've got to make some more noise.
			for ($i = 0; $i < 50; $i++) { echo '<span></span>'; }
			echo "\n\n";
		}

		// No maximum execution time limit and we're good to go!
		set_time_limit(0);

	}

	// Pushes an event using the proper technique (1: XHR streaming, 2: forever frame)
	function push($event) {
		switch ($this->cometTechnique) {
			case 1: echo '<comet>'.$event.'</comet><br />'."\n"; break;
			case 2: echo $event.'<script>parent.push(\''.str_replace('\'', '\\\'', $event).'\');</script><br />'."\n"; break;
		}
	}

}

?>